import 'package:flutter_house_manager/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  String _token = '';
  String _refreshToken = '';

  init() async {
    final prefs = await _getInstance(); // 存储对象 相当于鸿蒙首选项的 获取仓库
    _token = prefs.getString(GlobalVariable.TOKEN_KEY) ?? '';
    _refreshToken = prefs.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

  setToken(String token, {String? refreshToken}) async {
    final prefs = await _getInstance(); // 存储对象 相当于鸿蒙首选项的 获取仓库
    prefs.setString(GlobalVariable.TOKEN_KEY, token);
    prefs.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken ?? '');
    _token = token;
    _refreshToken = refreshToken ?? '';
  }

  // 3. 获取token 和 获取refreshToken
  String getToken() {
    // 存储对象 相当于鸿蒙首选项的 获取仓库
    return _token;
  }

  String getRefreshToken() {
    // 存储对象 相当于鸿蒙首选项的 获取仓库
    return _refreshToken;
  }

  removeToken() async {
    final prefs = await _getInstance(); // 存储对象 相当于鸿蒙首选项的 获取仓库
    prefs.remove(GlobalVariable.TOKEN_KEY);
    prefs.remove(GlobalVariable.REFRESH_TOKEN_KEY);
    _token = '';
    _refreshToken = '';
  }
}

final tokenManager = TokenManager();
